package org.summerframework.web.exception;

import org.summerframework.core.util.HandlerMethodUtil;
import org.summerframework.core.util.SpringContextUtil;
import org.summerframework.core.util.ViewUtil;
import org.summerframework.web.exception.resolver.UriExposeExceptionResolver;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石超
 * @version v1.0.0
 */
public class FilterFailureHandler {
    protected UriExposeExceptionResolver uriExposeExceptionResolver;

    protected RequestMappingHandlerMapping requestMappingHandlerMapping;

    public FilterFailureHandler() {
        this.uriExposeExceptionResolver = SpringContextUtil.getBean(UriExposeExceptionResolver.class);
        this.requestMappingHandlerMapping = SpringContextUtil.getBean(RequestMappingHandlerMapping.class);
    }

    public FilterFailureHandler(UriExposeExceptionResolver uriExposeExceptionResolver, RequestMappingHandlerMapping requestMappingHandlerMapping) {
        this.uriExposeExceptionResolver = uriExposeExceptionResolver;
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
    }

    public void failure(HttpServletRequest request, HttpServletResponse response, Exception authException) {
        HandlerExecutionChain handlerExecutionChain = HandlerMethodUtil.getHandlerMethod(requestMappingHandlerMapping, request);

        if (handlerExecutionChain != null) {
            ViewUtil.render(uriExposeExceptionResolver.resolveException(request, response, handlerExecutionChain.getHandler(), authException), request, response);
        } else {
            ViewUtil.render(uriExposeExceptionResolver.resolveException(request, response, null, authException), request, response);
        }
    }
}
